package com.zzyl.interceptor;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.zzyl.exception.BusinessException;
import com.zzyl.properties.JwtProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class WechatUserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取header中的token
        String token = request.getHeader("authorization");
        if (StrUtil.isEmpty(token)) {
            throw new BusinessException("登录状态失效,请重新登录");
        }

        //解析token
        Claims claims = JwtUtil.parseJWT(jwtProperties.getBase64EncodedSecretKey(), token);
        if (ObjectUtil.isEmpty(claims)) {
            throw new BusinessException("登录状态失效,请重新登录");
        }

        //获取用户id
        Long userId = MapUtil.get(claims, "userid", Long.class);
        if (ObjectUtil.isEmpty(userId)) {
            throw new BusinessException("登录状态失效,请重新登录");
        }

        //把数据存储到线程中
        UserThreadLocal.set(userId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}